<template>
  <div class="assign-network">
    <search-table
      :columns="columns"
      :data="assignNetworkList"
      @change-page="changePageNow"
      @change-size="changePageSize"
      :total="total"
      :page.sync="pageIndex"
      :size.sync="pageSize"
    >
      <template slot="button-group">
        <Button
          type="primary"
          ghost
          :disabled="disabledAllBtn"
          @click="showPublicIpModal"
          icon="md-options"
          >绑定/解绑外网IP</Button
        >
        <!-- <Poptip 
                  confirm 
                  title="你确定要解绑这些队伍吗"
                  transfer
                  @on-ok="batchUnbundleNetwork">
                  <Button
                      type="error"
                      ghost
                      :disabled="disabledAllBtn || checkedIds.length === 0"
                      icon="ios-trash-outline">批量解绑</Button>
              </Poptip> -->
      </template>
      <template slot="select-group">
        <Select filterable
          v-model="teamId"
          placeholder="请选择团队"
          filterable
          clearable
          @on-change="changePageNow(1)"
        >
          <Option
            v-for="item in currentTeamList"
            :value="item.id"
            :key="item.id"
            :title="item.name"
            >{{ item.name }}</Option
          >
        </Select>
      </template>
    </search-table>
    <Modal
      v-model="publicIpModal.show"
      width="800"
      :footer-hide="true"
      @on-visible-change="visibleChange"
      title="绑定/解绑外网IP"
    >
      <Transfer
        class="transfer"
        :data="transferList"
        :target-keys="targetKeys"
        filterable
        :filter-method="filterMethod"
        @on-change="handleChange"
      ></Transfer>
    </Modal>
  </div>
</template>

<script>
import SearchTable from '@/components/SearchTable/SearchTable'
import {
  getOperatingRecordList,
  batchUnbundlePublicIP,
  resetPublicIp,
  assigningPublicIP,
  getVNC,
  getInstanceList
} from '@/api/cloud'
import teamMixin from '@/mixin/groupMixin'

export default {
  name: 'assign-network',
  components: {
    SearchTable
  },
  mixins: [teamMixin],
  props: {
    disabledAllBtn: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      transferDisabledKey: [], // 穿梭框需要禁用的数据
      targetKeys: [], // 穿梭框数据
      teamId: '', // 搜索条件，团队名
      total: 0, // 总数据量
      pageSize: 10, // 分页大小
      pageIndex: 1, // 当前页
      publicIpModal: {
        show: false
      },
      columns: [
        {
          placement: 'top-left',
          title: '名称',
          key: 'teamName',
          align: 'center',
          tooltip: true,
          width: 230
        },
        {
          title: '分配时间',
          width: 150,
          key: 'createTime'
        },
        {
          title: '外网Ip',
          width: 120,
          key: 'publicIpAddress'
        },
        {
          title: '已重置次数',
          width: 120,
          key: 'residue'
        },
        {
          title: '密码',
          width: 120,
          key: 'password'
        },
        {
          placement: 'top-right',
          title: '绑定状态',
          width: 70,
          key: 'success',
          render: (h, params) => {
            let status = params.row.success
            return h(
              'Tag',
              {
                props: {
                  color: status ? 'var(--status-yes)' : 'var(--status-ing)'
                }
              },
              status ? '已绑定' : '绑定中'
            )
          }
        },
        {
          title: '操作',
          key: 'action',
          placement: 'top-right',
          opList: [
            {
              txt: '解绑',
              title: '你确定要解绑吗',
              tooltip: true,
              disabled: (data) => this.disabledAllBtn || !data.success,
              on: {
                click: (data) => {
                  this.batchUnbundleNetwork([data.id])
                }
              }
            },
            {
              txt: '重置',
              title: '你确定要重置吗',
              tooltip: true,
              disabled: (data) =>
                this.disabledAllBtn ||
                !data.success ||
                (this.resetLoading && this.currentInstanceId === data.instanceId),
              on: {
                click: (data) => {
                  this.resetNetwork(data.instanceId)
                }
              }
            },
            {
              txt: 'VNC接入',
              disabled: (data) => this.disabledAllBtn || !data.success || !data.instanceId,
              on: {
                click: (data) => {
                  this.getLoad(data.instanceId)
                }
              }
            }
          ]
          // render:(h,params) => {
          //     return h('div',[
          //         h('Poptip', {
          //             props: {
          //                 confirm: true,
          //                 type: 'error',
          //                 size: 'large',
          //                 title: '你确定要解绑吗',
          //                 transfer:true
          //             },
          //             on: {
          //                 'on-ok': () => {
          //                     this.batchUnbundleNetwork([params.row.id])
          //                 }
          //             }
          //         }, [
          //             h('Button', {
          //                 props: {
          //                     type: 'error',
          //                     size: 'small',
          //                     disabled: this.disabledAllBtn || !params.row.success
          //                 },
          //                 style: {
          //                     marginRight: '5px'
          //                 },
          //             }, '解绑')
          //         ]),
          //         h('Poptip', {
          //             props: {
          //                 confirm: true,
          //                 type: 'error',
          //                 size: 'large',
          //                 title: '你确定要重置吗',
          //                 transfer:true
          //             },
          //             on: {
          //                 'on-ok': () => {
          //                     this.resetNetwork(params.row.instanceId)
          //                 }
          //             }
          //         }, [
          //             h('Button', {
          //                 props: {
          //                     type: 'primary',
          //                     size: 'small',
          //                     disabled: this.disabledAllBtn || !params.row.success || (this.resetLoading && this.currentInstanceId === params.row.instanceId)
          //                 },
          //                 style: {
          //                     marginRight: '5px'
          //                 },
          //             }, '重置')
          //         ]),
          //         h('Button',{
          //             props: {
          //                 type: 'primary',
          //                 size: 'small',
          //                 disabled: this.disabledAllBtn || !params.row.success || !params.row.instanceId
          //             },
          //             style: {
          //                 marginRight: '5px'
          //             },
          //             on:{
          //                 click: () => {
          //                     this.getLoad(params.row.instanceId)
          //                 }
          //             }
          //         }, 'VNC接入'),
          //     ])
          // }
        }
      ],
      resetLoading: false,
      assignNetworkList: [] // 外网IP分配记录
    }
  },
  mounted() {
    this.getAssignNetworkList()
  },
  computed: {
    transferList() {
      return this.currentTeamList.map((item) => {
        return {
          key: item.id,
          label: item.name,
          disabled: this.transferDisabledKey.includes(item.id)
        }
      })
    },
    checkedIds() {
      let ids = []
      this.assignNetworkList.forEach((item) => {
        if (item.checked) {
          ids.push(item.id)
        }
      })
      return ids
    },
    currentTeamList() {
      // 过滤掉目标方管理员组
      return this.teamList.filter((item) => item.name !== '目标方管理员组')
    }
  },
  methods: {
    getInstanceLDetail(id) {
      return new Promise((resolve) => {
        getInstanceList({
          id
        })
          .then(({ code, data }) => {
            if (code === 1) {
              resolve((data && data.items && data.items[0]) || {})
            }
          })
          .catch(() => {
            resolve({})
          })
      })
    },
    // 打开vpc接入界面
    getLoad(id) {
      getVNC(id, { autoLogin: true })
        .then(({ code, data, message }) => {
          if (code === 1) {
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = data
            link.target = '_blank'
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          } else {
            this.$Message.warning(message)
          }
        })
        .catch(() => {
          this.$Message.error('连接VPC异常')
        })
    },
    // 隐藏绑定/解绑模态框时，清空定时任务
    visibleChange() {
      clearTimeout(this.allListTimer)
    },
    // 绑定外网IP
    bundleNetwork(allTeamIds, teamIds) {
      let data = []
      this.currentTeamList.forEach((item) => {
        if (teamIds.includes(item.id)) {
          data.push({
            teamId: item.id,
            teamName: item.name,
            partyId: item.partyId
          })
        }
      })
      assigningPublicIP(this.$route.query.id, this.$route.query.prjid, data)
        .then(({ code, message }) => {
          if (code !== 1) {
            this.$Message.warning(message)
            return
          }
          this.targetKeys = allTeamIds
          this.teamId = ''
          this.$Message.info('分配外网IP成功，正在绑定中')
          this.changePageNow(1)
          this.$emit('add-data')
        })
        .catch(() => {
          this.$Message.error('分配外网IP异常')
        })
    },
    // 穿梭框过滤方法
    filterMethod(data, query) {
      return data.label.indexOf(query) > -1
    },
    // 处理穿梭框数据变化的方法
    handleChange(targetKeys, direction, moveKeys) {
      if (direction === 'right') {
        this.bundleNetwork(targetKeys, moveKeys)
      } else {
        this.batchUnbundleNetwork(moveKeys, targetKeys, true)
      }
    },
    // 显示外网IP绑定模态框
    showPublicIpModal() {
      this.publicIpModal.show = true
      // 查询所有已绑定的团队的外网IP数据
      this.getAllAssignNetworkList()
    },
    // 查询所有的外网分配记录
    getAllAssignNetworkList() {
      clearTimeout(this.allListTimer)
      getOperatingRecordList({
        pageIndex: 1,
        pageSize: 2147483646,
        sceneId: this.$route.query.id
      })
        .then(({ code, message, data }) => {
          if (code !== 1) {
            this.$Message.warning(message)
            return
          }
          let transferDisabledKey = [],
            targetKeys = []
          data.items.forEach((item) => {
            targetKeys.push(item.teamId)
            if (!item.success) {
              transferDisabledKey.push(item.teamId)
            }
          })
          this.transferDisabledKey = transferDisabledKey
          this.targetKeys = targetKeys
        })
        .catch(() => {
          this.$Message.error('获取全部外网分配列表异常')
        })
        .finally(() => {
          this.allListTimer = setTimeout(() => {
            this.getAllAssignNetworkList()
          }, 10000)
        })
    },
    // 批量解绑外网IP
    batchUnbundleNetwork(ids = this.checkedIds, targetKeys, isTransfer) {
      if (isTransfer) {
        // 是穿梭框操作，传递的是团队ID，需要遍历列表获取主键ID
        ids = this.assignNetworkList
          .filter((item) => ids.includes(item.teamId))
          .map((item) => item.id)
      }
      batchUnbundlePublicIP(ids)
        .then(({ code, message }) => {
          if (code !== 1) {
            this.$Message.warning(message)
            return
          }
          this.$Message.info('解绑外网IP成功')
          this.pageIndex =
            this.assignNetworkList.length === ids.length && this.pageIndex > 1
              ? this.pageIndex - 1
              : this.pageIndex
          this.targetKeys = targetKeys
          this.getAssignNetworkList()
          this.$emit('del-data')
        })
        .catch(() => {
          this.$Message.error('解绑外网IP异常')
        })
    },
    // 修改分页大小
    changePageSize(val) {
      this.pageSize = val
      this.getAssignNetworkList()
    },
    // 修改当前页
    changePageNow(val) {
      this.pageIndex = val
      this.getAssignNetworkList()
    },
    // 获取外网分配列表
    getAssignNetworkList() {
      clearTimeout(this.listTimer)
      getOperatingRecordList({
        pageIndex: this.pageIndex,
        pageSize: this.pageSize,
        teamId: this.teamId,
        sceneId: this.$route.query.id
      })
        .then(async ({ code, message, data }) => {
          if (code !== 1) {
            this.$Message.warning(message)
            return
          }
          this.total = data.total || 0
          let list = data.items || []
          for (let i = 0, length = list.length; i < length; i++) {
            let item = list[i]
            await this.getInstanceLDetail(item.instanceId).then((res) => {
              item.password = res.password
            })
          }
          this.assignNetworkList = list
          if (this.total == 0) {
            // 创建的数据又被删了
            this.$emit('del-data')
          }
        })
        .catch(() => {
          this.$Message.error('获取外网分配列表异常')
        })
        .finally(() => {
          this.listTimer = setTimeout(() => {
            this.getAssignNetworkList()
          }, 10000)
        })
    },
    // 重置外网IP
    resetNetwork(id) {
      this.currentInstanceId = id
      this.resetLoading = true
      resetPublicIp(id)
        .then(({ code, message }) => {
          if (code !== 1) {
            this.$Message.warning(message)
            return
          }
          this.$Message.info('重置成功')
          this.getAssignNetworkList()
        })
        .catch(() => {
          this.$Message.error('重置异常')
        })
        .finally(() => {
          this.resetLoading = false
        })
    }
  },
  watch: {},
  beforeDestroy() {
    clearTimeout(this.listTimer)
    clearTimeout(this.allListTimer)
  }
}
</script>

<style scoped>
.transfer {
  width: 100%;
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.transfer /deep/ .ivu-transfer-list {
  width: calc(50% - 20px);
  height: 100%;
}
</style>
